# coding: utf8

#########################################################################
## This scaffolding model makes your app work on Google App Engine too
#########################################################################

if request.env.web2py_runtime_gae:            # if running on Google App Engine
    db = DAL('gae')                           # connect to Google BigTable
    session.connect(request, response, db=db) # and store sessions and tickets there
    ### or use the following lines to store sessions in Memcache
    # from gluon.contrib.memdb import MEMDB
    # from google.appengine.api.memcache import Client
    # session.connect(request, response, db=MEMDB(Client())
else:                                         # else use a normal relational database
    db = DAL('sqlite://storage.sqlite')       # if not, use SQLite or other DB
## if no need for session
# session.forget()

#########################################################################
## Here is sample code if you need for 
## - email capabilities
## - authentication (registration, login, logout, ... )
## - authorization (role based authorization)
## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)
## - crud actions
## comment/uncomment as needed

from gluon.tools import *

crud=Crud(globals(),db)            # for CRUD helpers using auth
service=Service(globals())         # for json, xml, jsonrpc, xmlrpc, amfrpc

mail=Mail()

if not request.env.http_host.split(":")[0]=="localhost":
    mail.settings.server='gae'
else:
    mail.settings.server='smtp.gmail.com:587'

mail.settings.sender="example_user@gmail.com"
mail.settings.login="example_user@gmail.com:example_pass" or None # if no TLS

auth=Auth(globals(),db)

auth.settings.table_user = db.define_table("auth_user",
     db.Field("first_name", length=128, default=""),
     db.Field("last_name", length=128, default=""),
     db.Field("email", length=128, default=""),
     db.Field("username", length=128, default=""),
     db.Field("password", "password", readable=False, label="Password"),
     db.Field("registration_key", length=128,
              writable=False, readable=False, default="")
)


t = auth.settings.table_user
t.first_name.requires = IS_NOT_EMPTY()
t.last_name.requires = IS_NOT_EMPTY()
t.password.requires = CRYPT() # password will be stored hashed
t.username.requires = [IS_NOT_EMPTY(), IS_NOT_IN_DB(db, db.auth_user.username)]
t.email.requires = [IS_EMAIL(), IS_NOT_IN_DB(db, db.auth_user.email)]
auth.define_tables()

recap_public_key  = '6LeKeAcAAAAAAI7YAdNowgSVwCAMzk8s3kZlZ0WG'
recap_private_key = '6LeKeAcAAAAAAFzwlLLmecTzh79uId0nMm5epAY6'

auth.settings.mailer = mail
auth.settings.captcha = Recaptcha(request,recap_public_key,recap_private_key)
auth.settings.captcha.error_message = T('invalid captcha')

auth.settings.registration_requires_approval = False
auth.settings.registration_requires_verification = True
auth.settings.mailer = mail

auth.messages.logged_out = T('You have been logged out successfully')
auth.messages.logged_in = T('You have been logged in successfully')
auth.messages.registration_successful = T('Registration successful')
#auth.messages.registration_on_mail = T('Registration successful, please check your email')
auth.messages.email_verified = T('Email verified')
auth.messages.email_sent = T('Email sent')
auth.messages.invalid_login = T('Invalid login, please try again')
auth.messages.profile_updated = T('Your profile have been udated successfully')
auth.messages.password_changed = T('Your password has been changed successfully')
auth.messages.new_password_sent = T('A new password was emailed to you')
auth.messages.mismatched_password = T('passwords do not match')
auth.messages.profile_updated = T('Profile updated')
auth.messages.new_password = T('New password')
auth.messages.old_password = T('Old password')
auth.messages.delete_label = T('Check to delete:')
auth.messages.invalid_email = T('invalid email')
auth.messages.verify_email = \
    'Click on the link http://' + request.env.http_host + \
        '/init/default/user/verify_email/%(key)s to verify your email'
#auth.messages.empty_field = T('this field cannot be empty')
#auth.messages.change_old_password = T('value not in database')
#auth.messages.change_new_password1 = ''
#auth.messages.change_new_password2 = ''
#auth.messages.change_password_match = T("new passwords don't match")

from datetime import datetime
from datetime import timedelta

class IS_IN_MY_DELETE_SET(object):

    def __init__(self,theset,
                    error_message = "Invalid date for removal"):
        self.theset = [str(item) for item in theset]
        self.error_message = error_message
        self.multiple = False

    def __call__(self,value):

        if value in self.theset:
            now = datetime.now
            if value == "one year":
                value = now() + timedelta(weeks=52)
            elif value == "one day":
                value = now() + timedelta(days=1)
            elif value == "one week":
                value = now() + timedelta(days=7)
            elif value == "one month":
                value = now() + timedelta(days=30)
            elif value == "one decade":
                value = now() + timedelta(weeks=520)
            elif value == "one millenium":
                value = now() + timedelta(weeks=52000)
            else:
                return (value,self.error_message)
            return (value,None)
        else:
           return (value,self.error_message)

    def options(self):
        return [(k, k) for (i, k) in enumerate(self.theset)]


db.define_table("note",
    Field("title", "string", length=128),
    Field("body", "text", length=1024),
    Field("priority", "string", default="low"),
    Field("removal_date", "datetime", default=request.now),
    Field("created_on","datetime"),
    Field("user_id", "integer"),
)

__now    = datetime.now()
__date   = datetime(__now.year, __now.month, __now.day, __now.hour, __now.minute, __now.second)
__date   = __date + timedelta(seconds=3600)
__f_year       = datetime(__now.year + 1, __now.month, __now.day)
__f_decade     = datetime(__now.year + 10, __now.month, __now.day)
__f_century    = datetime(__now.year + 100, __now.month, __now.day)
__f_millenuim  = datetime(__now.year + 1000, __now.month, __now.day)
__removal = (
    (__date + timedelta(seconds=60)),
    (__date + timedelta(days=1)),
    (__date + timedelta(days=7)),
    (__f_year),
    (__f_decade)
)
__removal_labels = ("one minute","one day","one week","one year","one decade")

db.note.body.requires = [IS_NOT_EMPTY(), IS_LENGTH(1024)]
db.note.body.label = "content"

db.note.title.requires = IS_LENGTH(64)
db.note.title.label = "title"

db.note.removal_date.requires = IS_IN_SET(__removal,labels=__removal_labels)
db.note.removal_date.label = T("delete after")

db.note.priority.requires = IS_IN_SET(("low","normal","high","critical","lifesaver"))
db.note.priority.label = T("priority")

db.note.created_on.default = request.now
db.note.created_on.writable = False
db.note.created_on.readable = False

db.note.user_id.writable = False
db.note.user_id.readable = False
db.note.user_id.default  = auth.user.id if auth.user else 0

#########################################################################
## Define your tables below, for example
##
## >>> db.define_table('mytable',Field('myfield','string'))
##
## Fields can be 'string','text','password','integer','double','boolean'
##       'date','time','datetime','blob','upload', 'reference TABLENAME'
## There is an implicit 'id integer autoincrement' field
## Consult manual for more options, validators, etc.
##
## More API examples for controllers:
##
## >>> db.mytable.insert(myfield='value')
## >>> rows=db(db.table.myfield=='value).select(db.mytable.ALL)
## >>> for row in rows: print row.id, row.myfield
#########################################################################
